<template>
    <div class="disease-science-management">
        <h4>疾病科普</h4>

        <!-- 筛选区域 -->
        <el-card class="filter-card">
            <div class="filter-container">
                <div class="filter-item">
                    <span class="filter-label">输入标题或关键字：</span>
                    <el-input v-model="filterForm.keyword" style="width: 200px" placeholder="输入标题或关键字" clearable />

                    <span class="filter-label">疾病类型：</span>
                    <el-select v-model="filterForm.diseaseType" placeholder="请选择疾病类型" style="width: 150px;" clearable>
                        <el-option label="内科" value="内科" />
                        <el-option label="外科" value="外科" />
                        <el-option label="妇科" value="妇科" />
                        <el-option label="儿科" value="儿科" />
                        <el-option label="皮肤科" value="皮肤科" />
                        <el-option label="眼科" value="眼科" />
                        <el-option label="口腔科" value="口腔科" />
                        <el-option label="心理科" value="心理科" />
                        <el-option label="营养科" value="营养科" />
                    </el-select>

                    <span class="filter-label">上传时间：</span>
                    <el-date-picker v-model="filterForm.startTime" type="date" placeholder="开始时间" style="width: 140px"
                        format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
                    <el-date-picker v-model="filterForm.endTime" type="date" placeholder="结束时间" style="width: 140px"
                        format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
                </div>
                <br>
                <el-button type="primary" @click="handleFilterImmediate" :loading="loading">筛选</el-button>
                <el-button @click="resetFilter" style="margin-left: 10px;">重置</el-button>
            </div>
        </el-card>

        <!-- 数据列表 -->
        <el-card class="list-card">
            <div class="list-header">
                <h5>数据列表</h5>
                <div class="list-actions">
                    <el-button type="success" @click="handleAdd" :disabled="loading || deleteLoading">新增文章</el-button>
                    <el-tag v-if="loading" type="info" size="small">
                        <el-icon class="is-loading">
                            <Loading />
                        </el-icon>
                        加载中...
                    </el-tag>
                    <el-tag v-else-if="tableData.length > 0" type="success" size="small">
                        已加载 {{ tableData.length }} 条数据
                    </el-tag>
                </div>
            </div>

            <el-table ref="tableRef" :data="tableData" border style="width: 100%"
                @selection-change="handleSelectionChange" v-loading="loading || deleteLoading" empty-text="暂无疾病科普数据"
                :row-key="(row: any) => row.id" :default-sort="{ prop: 'uploadTime', order: 'descending' }">
                <el-table-column type="selection" width="55" :selectable="() => !deleteLoading" />
                <el-table-column prop="popularScienceTitle" label="标题" width="180">
                    <template #default="scope">
                        {{ scope.row.popularScienceTitle || scope.row.title }}
                    </template>
                </el-table-column>
                <el-table-column label="列表图" width="120">
                    <template #default="scope">
                        <el-image :src="scope.row.popularScienceImages || scope.row.image"
                            :preview-src-list="[scope.row.popularScienceImages || scope.row.image]" fit="cover"
                            style="width: 80px; height: 45px; border-radius: 4px;" />
                    </template>
                </el-table-column>
                <el-table-column prop="diseaseType" label="分类" width="100">
                    <template #default="scope">
                        {{ scope.row.diseaseType || scope.row.category }}
                    </template>
                </el-table-column>
                <el-table-column prop="createdBy" label="上传人" width="100">
                    <template #default="scope">
                        {{ scope.row.createdBy || 'admin' }}
                    </template>
                </el-table-column>
                <el-table-column prop="views" label="浏览次数" width="100" />
                <el-table-column prop="uploadTime" label="上传时间">
                    <template #default="scope">
                        {{ moment(scope.row.uploadTime).format('YYYY-MM-DD HH:mm:ss') }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="260">
                    <template #default="scope">
                        <el-button type="primary" size="small" @click="handleViewDetail(scope.row)"
                            :disabled="loading || deleteLoading">查看详情</el-button>
                        <el-button type="warning" size="small" @click="handleEdit(scope.row)"
                            :disabled="loading || deleteLoading">编辑</el-button>
                        <el-button type="danger" size="small" @click="handleDelete(scope.row)" :loading="deleteLoading"
                            :disabled="deleteLoading">逻辑删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination-container">
                <div class="pagination-left">
                    <el-checkbox v-model="selectAll" @change="handleSelectAll"
                        :disabled="deleteLoading || loading">全选</el-checkbox>
                    <el-button type="danger" size="small" @click="handleBatchDelete"
                        :disabled="selectedRows.length === 0 || deleteLoading"
                        :loading="deleteLoading">批量逻辑删除</el-button>
                    <span class="pagination-info">共{{ page.pageCount }}页/{{ page.totalCount }}条数据</span>
                </div>
                <el-pagination v-model:current-page="page.PageIndex" v-model:page-size="page.PageSize"
                    :page-sizes="[10, 20, 50, 100]" :total="page.totalCount"
                    layout="total, sizes, prev, pager, next, jumper" prev-text="上一页" next-text="下一页"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </el-card>

        <!-- 新增/编辑对话框 -->
        <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '新增疾病科普' : '编辑疾病科普'" width="800px"
            @close="resetForm">
            <el-button type="primary" @click="dialogVisible = false"
                style="float: right; margin-bottom: 20px;">返回</el-button>



            <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px" label-position="right">
                <el-form-item label="分类" prop="category">
                    <el-select v-model="formData.category" placeholder="请选择分类" style="width: 200px;">
                        <el-option label="内科" value="内科" />
                        <el-option label="外科" value="外科" />
                        <el-option label="妇科" value="妇科" />
                        <el-option label="儿科" value="儿科" />
                        <el-option label="皮肤科" value="皮肤科" />
                        <el-option label="眼科" value="眼科" />
                        <el-option label="口腔科" value="口腔科" />
                        <el-option label="心理科" value="心理科" />
                        <el-option label="营养科" value="营养科" />
                    </el-select>
                    <el-select v-model="formData.subCategory" placeholder="请选择疾病"
                        style="width: 200px; margin-left: 10px;">
                        <el-option v-for="disease in diseaseOptions" :key="disease" :label="disease" :value="disease" />
                    </el-select>
                </el-form-item>

                <el-form-item label="标题" prop="title">
                    <el-input v-model="formData.title" placeholder="请输入标题..." />
                </el-form-item>

                <el-form-item label="列表图" prop="image">
                    <el-upload class="image-upload" :action="uploadUrl" :headers="uploadHeaders" :show-file-list="false"
                        :on-success="handleUploadSuccess" :on-error="handleUploadError" :before-upload="beforeUpload"
                        :on-progress="handleUploadProgress" :data="uploadData" name="imageFile" accept="image/*"
                        :multiple="false" drag v-loading="uploadLoading">
                        <div class="upload-area" :class="{ 'upload-success': uploadSuccess }">
                            <el-image v-if="formData.image" :src="formData.image" fit="cover"
                                style="width: 100%; height: 100%; border-radius: 4px;"
                                :preview-src-list="[formData.image]" preview-teleported />
                            <div v-else class="upload-placeholder">
                                <el-icon>
                                    <Plus />
                                </el-icon>
                                <div class="upload-text">点击上传图片</div>
                            </div>
                            <!-- 上传成功后的覆盖层 -->
                            <div v-if="formData.image" class="upload-overlay">
                                <div class="upload-success-icon">
                                    <el-icon color="#67c23a" size="24">
                                        <Check />
                                    </el-icon>
                                </div>
                            </div>
                            <!-- 上传成功提示 -->
                            <div v-if="uploadSuccess" class="upload-success-message">
                                <el-icon color="#67c23a" size="20">
                                    <Check />
                                </el-icon>
                                <span>上传成功</span>
                            </div>
                        </div>
                    </el-upload>
                    <div class="upload-tip">建议尺寸120*90，不要超过1M</div>
                    <!-- 图片信息显示 -->
                    <div v-if="formData.image" class="image-info">
                        <el-tag size="small" type="success">已上传</el-tag>
                        <el-button size="small" type="primary" @click="reuploadImage">重新上传</el-button>
                    </div>
                </el-form-item>

                <el-form-item label="状态" prop="status">
                    <el-switch v-model="formData.status" active-text="启用" inactive-text="禁用" />
                </el-form-item>

                <el-form-item label="是否推荐" prop="isRecommend">
                    <el-radio-group v-model="formData.isRecommend">
                        <el-radio :label="true">是</el-radio>
                        <el-radio :label="false">否</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="详细内容" prop="content">
                    <div class="rich-text-editor">
                        <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef"
                            :defaultConfig="toolbarConfig" mode="default" />
                        <Editor style="height: 400px; overflow-y: hidden;" v-model="formData.content"
                            :defaultConfig="editorConfig" mode="default" @onCreated="handleCreated" />
                    </div>
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="resetForm">取消</el-button>
                    <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
                        {{ dialogType === 'add' ? '提交' : '更新' }}
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 详情对话框 -->
        <el-dialog v-model="detailDialogVisible" title="疾病科普详情" width="900px">
            <div class="disease-detail">
                <div class="detail-section">
                    <h3>基本信息</h3>
                    <div class="detail-content">
                        <div class="detail-left">
                            <el-image :src="currentDisease.popularScienceImages || currentDisease.image"
                                style="width: 200px; height: 150px; border-radius: 8px;" fit="cover"
                                :preview-src-list="[currentDisease.popularScienceImages || currentDisease.image]" />
                        </div>
                        <div class="detail-right">
                            <table class="detail-table">
                                <tbody>
                                    <tr>
                                        <td class="label">ID</td>
                                        <td>{{ currentDisease.id || '01' }}</td>
                                        <td class="label">标题</td>
                                        <td>{{ currentDisease.popularScienceTitle || currentDisease.title }}</td>
                                    </tr>
                                    <tr>
                                        <td class="label">分类</td>
                                        <td>{{ currentDisease.diseaseType || currentDisease.category }}</td>
                                        <td class="label">疾病类型</td>
                                        <td>{{ currentDisease.subCategory }}</td>
                                    </tr>
                                    <tr>
                                        <td class="label">状态</td>
                                        <td>{{ (currentDisease.popularScienceStatus !== undefined ?
                                            currentDisease.popularScienceStatus : currentDisease.status) ? '启用' : '禁用'
                                        }}</td>
                                        <td class="label">是否推荐</td>
                                        <td>{{ (currentDisease.isRecommended !== undefined ?
                                            currentDisease.isRecommended :
                                            currentDisease.isRecommend) ? '是' : '否' }}</td>
                                    </tr>
                                    <tr>
                                        <td class="label">浏览次数</td>
                                        <td>{{ currentDisease.views }}</td>
                                        <td class="label">上传人</td>
                                        <td>{{ currentDisease.createdBy || 'admin' }}</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <div class="detail-section">
                    <h3>详细内容</h3>
                    <div class="disease-content">
                        <div v-if="currentDisease.detailedContent || currentDisease.content"
                            v-html="currentDisease.detailedContent || currentDisease.content" class="rich-content">
                        </div>
                        <div v-else class="default-content">
                            <p>暂无详细内容。</p>
                        </div>
                    </div>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, computed, watch, onBeforeUnmount, shallowRef, nextTick } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Plus, Check, Loading } from '@element-plus/icons-vue'
import {
    readB,
    writeB,
    addPopularization,
    getPopularizationList,
    updatePopularization,
    deletePopularization,
    batchDeletePopularization,
    getPopularizationDetail,
    type PopularizationData
} from '@/api/http'
import moment from 'moment'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { createEditor, createToolbar } from '@wangeditor/editor'
// @ts-ignore
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

// 响应式数据
const tableData = ref<any[]>([])
const loading = ref(false)
const deleteLoading = ref(false)
const submitLoading = ref(false)
const uploadLoading = ref(false)
const uploadSuccess = ref(false)
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const formRef = ref<FormInstance>()
const tableRef = ref()
const selectedRows = ref<any[]>([])
const selectAll = ref(false)
const currentDisease = ref<any>({})

// 富文本编辑器相关
const editorRef = shallowRef()

// 工具栏配置
const toolbarConfig = {
    excludeKeys: ['group-video', 'insertVideo', 'uploadVideo', 'codeBlock']
}

// 编辑器配置
const editorConfig = {
    placeholder: '请输入疾病科普详细内容...',
    MENU_CONF: {
        uploadImage: {
            server: 'http://localhost:5023/api/Carousel/UploadCarouselImage/upload-image?bucketName=image&prefix=disease',
            fieldName: 'imageFile',
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('token') || ''}`
            },
            onSuccess(file: any, res: any) {
                console.log('富文本图片上传成功', file, res)
                if (res && res.code === 200) {
                    const imageUrl = res.data?.url || res.data || res
                    if (imageUrl) {
                        // 将图片URL插入到编辑器中
                        const editor = editorRef.value
                        if (editor) {
                            editor.insertImage({
                                url: imageUrl,
                                alt: file.name,
                                href: imageUrl
                            })
                        }
                    }
                }
            },
            onFailed(file: any, res: any) {
                console.log('富文本图片上传失败', file, res)
                ElMessage.error(res?.message || '图片上传失败')
            },
            onError(file: any, err: any) {
                console.error('富文本图片上传错误', file, err)
                ElMessage.error('图片上传失败')
            }
        }
    }
}

// 筛选表单
const filterForm = reactive({
    keyword: '',
    diseaseType: '',
    startTime: '',
    endTime: ''
})

// 分页参数
const page = reactive({
    PageIndex: 1,
    PageSize: 10,
    totalCount: 0,
    pageCount: 0
})

// 表单数据
const formData = reactive({
    id: 0,
    title: '',
    image: '',
    category: '',
    subCategory: '',
    status: true,
    isRecommend: false,
    content: ''
})

// 疾病类型选项
const diseaseOptions = computed(() => {
    const diseaseMap: { [key: string]: string[] } = {
        '内科': ['冠心病', '高血压', '糖尿病', '胃炎', '感冒发烧'],
        '外科': ['阑尾炎', '胆结石', '骨折', '外伤', '肿瘤'],
        '妇科': ['月经不调', '妇科炎症', '子宫肌瘤', '卵巢囊肿'],
        '儿科': ['小儿感冒', '小儿发烧', '小儿腹泻', '疫苗接种'],
        '皮肤科': ['湿疹', '痤疮', '皮炎', '荨麻疹'],
        '眼科': ['近视', '白内障', '青光眼', '结膜炎'],
        '口腔科': ['蛀牙', '牙龈炎', '口腔溃疡', '牙周病'],
        '心理科': ['抑郁症', '焦虑症', '失眠', '强迫症'],
        '营养科': ['营养不良', '肥胖', '饮食调理', '营养搭配']
    }
    return diseaseMap[formData.category] || []
})

// 表单验证规则
const formRules: FormRules = {
    title: [
        { required: true, message: '请输入标题', trigger: 'blur' }
    ],
    category: [
        { required: true, message: '请选择分类', trigger: 'change' }
    ],
    subCategory: [
        { required: true, message: '请选择疾病类型', trigger: 'change' }
    ],
    image: [
        { required: true, message: '请上传列表图', trigger: 'change' }
    ],
    content: [
        { required: true, message: '请输入详细内容', trigger: 'blur' }
    ]
}

// 上传相关
const uploadUrl = 'http://47.95.68.41:4560/api/Carousel/UploadCarouselImage/upload-image?bucketName=image&prefix=disease'
const uploadHeaders = {
    'Authorization': `Bearer ${localStorage.getItem('token') || ''}`
}
const uploadData = {
    bucketName: 'image',
    prefix: 'disease'
}

// 模拟数据（实际项目中应该从API获取）
const mockData = [
    {
        id: '1',
        title: '发烧了要捂汗才能好得快吗？',
        image: 'https://via.placeholder.com/120x90',
        category: '内科',
        subCategory: '感冒发烧',
        createdBy: 'admin',
        views: 9555,
        uploadTime: '2019-02-07 21:00:00',
        status: true,
        isRecommend: true,
        content: '<p>发烧是宝宝成长过程中最常见的疾病，作为爸妈的心疼又着急！民间的土办法说："发烧只要"捂出汗"就好了，我们从小就被妈妈这样干过，那这个"土办法"到底管不管用，值不值得我们去"传一传"呢？</p>'
    },
    {
        id: '2',
        title: '高血压的预防与治疗',
        image: 'https://via.placeholder.com/120x90',
        category: '内科',
        subCategory: '高血压',
        createdBy: 'admin',
        views: 3421,
        uploadTime: '2019-02-07 21:00:00',
        status: true,
        isRecommend: false,
        content: '<p>高血压是一种常见的慢性疾病...</p>'
    }
]

// 获取疾病科普列表
const getDiseaseList = async () => {
    loading.value = true
    try {
        const params = {
            PageIndex: page.PageIndex,
            PageSize: page.PageSize,
            PopularScienceTitle: filterForm.keyword || undefined,
            DiseaseType: filterForm.diseaseType || undefined,
            StartTime: filterForm.startTime || undefined,
            EndTime: filterForm.endTime || undefined
        }

        const response = await getPopularizationList(params)

        if (response.data && response.data.code === 200) {
            tableData.value = response.data.data || []
            page.totalCount = response.data.data.totalCount || 0
            page.pageCount = response.data.data.pageCount || 0
        } else {
            // 如果API调用失败，使用模拟数据
            let filteredData = [...mockData]

            if (filterForm.keyword) {
                filteredData = filteredData.filter(item =>
                    item.title.includes(filterForm.keyword) ||
                    item.category.includes(filterForm.keyword)
                )
            }

            if (filterForm.diseaseType) {
                filteredData = filteredData.filter(item =>
                    item.category === filterForm.diseaseType
                )
            }

            tableData.value = filteredData
            page.totalCount = filteredData.length
            page.pageCount = Math.ceil(page.totalCount / page.PageSize)
        }

        selectedRows.value = []
        selectAll.value = false
        if (tableRef.value) {
            tableRef.value.clearSelection()
        }

        loading.value = false
    } catch (error) {
        console.error('获取疾病科普列表失败:', error)
        // 使用模拟数据作为后备
        let filteredData = [...mockData]

        if (filterForm.keyword) {
            filteredData = filteredData.filter(item =>
                item.title.includes(filterForm.keyword) ||
                item.category.includes(filterForm.keyword)
            )
        }

        if (filterForm.diseaseType) {
            filteredData = filteredData.filter(item =>
                item.category === filterForm.diseaseType
            )
        }

        tableData.value = filteredData
        page.totalCount = filteredData.length
        page.pageCount = Math.ceil(page.totalCount / page.PageSize)

        selectedRows.value = []
        selectAll.value = false
        if (tableRef.value) {
            tableRef.value.clearSelection()
        }

        loading.value = false
        ElMessage.warning('获取数据失败，显示模拟数据')
    }
}

// 筛选处理
const handleFilterImmediate = () => {
    page.PageIndex = 1
    getDiseaseList()
}

// 重置筛选
const resetFilter = () => {
    Object.assign(filterForm, {
        keyword: '',
        diseaseType: '',
        startTime: '',
        endTime: ''
    })
    page.PageIndex = 1
    getDiseaseList()
}



// 新增
const handleAdd = () => {
    dialogType.value = 'add'
    resetForm()
    dialogVisible.value = true
    console.log('新增对话框已打开，类型:', dialogType.value)
}

// 编辑
const handleEdit = (row: any) => {
    dialogType.value = 'edit'

    // 处理疾病类型，将其拆分为分类和子分类
    const diseaseTypeParts = row.diseaseType ? row.diseaseType.split('-') : []
    const category = diseaseTypeParts[0] || row.category || ''
    const subCategory = diseaseTypeParts[1] || row.subCategory || ''

    Object.assign(formData, {
        id: parseInt(row.id) || 0, // 确保ID是数字类型
        title: row.popularScienceTitle || row.title,
        image: row.popularScienceImages || row.image,
        category: category,
        subCategory: subCategory,
        status: row.popularScienceStatus !== undefined ? row.popularScienceStatus : row.status,
        isRecommend: row.isRecommended !== undefined ? row.isRecommended : row.isRecommend,
        content: row.detailedContent || row.content
    })

    dialogVisible.value = true
}

// 查看详情
const handleViewDetail = async (row: any) => {
    try {
        const response = await getPopularizationDetail(row.id)

        if (response.data && response.data.code === 200) {
            currentDisease.value = response.data.data
        } else {
            // 如果API调用失败，使用当前行数据
            currentDisease.value = { ...row }
        }

        detailDialogVisible.value = true
    } catch (error) {
        console.error('获取详情失败:', error)
        // 使用当前行数据作为后备
        currentDisease.value = { ...row }
        detailDialogVisible.value = true
        ElMessage.warning('获取详情失败，显示基本信息')
    }
}

// 删除
const handleDelete = async (row: any) => {
    try {
        await ElMessageBox.confirm(
            `确定要逻辑删除以下疾病科普吗？\n\n标题：${row.popularScienceTitle || row.title}\n分类：${row.diseaseType || row.category}\n\n删除后数据将不可见，但不会从数据库中彻底删除。`,
            '逻辑删除确认',
            {
                confirmButtonText: '确定删除',
                cancelButtonText: '取消',
                type: 'warning',
                dangerouslyUseHTMLString: false,
                customClass: 'delete-confirm-dialog'
            }
        )

        console.log('删除疾病科普:', row)

        // 设置删除加载状态
        deleteLoading.value = true

        const response = await deletePopularization(parseInt(row.id) || 0)

        console.log('删除API响应:', response)

        if (response.data && response.data.code === 200) {
            ElMessage.success(`逻辑删除成功：${row.popularScienceTitle || row.title}`)
            getDiseaseList()
        } else {
            const errorMessage = response.data?.message || '逻辑删除失败'
            ElMessage.error(errorMessage)
        }

        deleteLoading.value = false
    } catch (error: any) {
        deleteLoading.value = false

        if (error === 'cancel') {
            // 用户取消删除
            return
        }

        console.error('删除失败:', error)
        let errorMessage = '逻辑删除失败'

        if (error.response) {
            const status = error.response.status
            const data = error.response.data

            if (status === 400) {
                errorMessage = data?.message || '请求参数错误'
            } else if (status === 401) {
                errorMessage = '未授权，请重新登录'
            } else if (status === 403) {
                errorMessage = '没有权限删除此数据'
            } else if (status === 404) {
                errorMessage = '要删除的数据不存在'
            } else if (status === 500) {
                errorMessage = '服务器内部错误'
            } else {
                errorMessage = data?.message || `HTTP ${status} 错误`
            }
        } else if (error.message) {
            errorMessage = error.message
        }

        ElMessage.error(errorMessage)
    }
}

// 批量删除
const handleBatchDelete = async () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请选择要删除的数据')
        return
    }

    // 构建删除列表信息
    const deleteList = selectedRows.value.map(row =>
        `• ${row.popularScienceTitle || row.title} (${row.diseaseType || row.category})`
    ).join('\n')
    const confirmMessage = `确定要逻辑删除以下 ${selectedRows.value.length} 条疾病科普吗？\n\n${deleteList}\n\n删除后数据将不可见，但不会从数据库中彻底删除。`

    try {
        await ElMessageBox.confirm(confirmMessage, '批量逻辑删除确认', {
            confirmButtonText: `确定删除 ${selectedRows.value.length} 条`,
            cancelButtonText: '取消',
            type: 'warning',
            dangerouslyUseHTMLString: false,
            customClass: 'batch-delete-confirm-dialog'
        })

        console.log('批量删除疾病科普:', selectedRows.value)

        // 提取所有选中ID
        const ids = selectedRows.value.map(row => parseInt(row.id) || 0)

        console.log('批量删除ID列表:', ids)

        // 设置删除加载状态
        deleteLoading.value = true

        const response = await batchDeletePopularization(ids)

        console.log('批量删除API响应:', response)

        if (response.data && response.data.code === 200) {
            ElMessage.success(`批量逻辑删除成功，共删除 ${ids.length} 条疾病科普`)
            // 清空选中状态
            selectedRows.value = []
            selectAll.value = false
            if (tableRef.value) {
                tableRef.value.clearSelection()
            }
            getDiseaseList()
        } else {
            const errorMessage = response.data?.message || '批量逻辑删除失败'
            ElMessage.error(errorMessage)
        }

        deleteLoading.value = false
    } catch (error: any) {
        deleteLoading.value = false

        if (error === 'cancel') {
            // 用户取消删除
            return
        }

        console.error('批量删除失败:', error)
        let errorMessage = '批量逻辑删除失败'

        if (error.response) {
            const status = error.response.status
            const data = error.response.data

            if (status === 400) {
                errorMessage = data?.message || '请求参数错误'
            } else if (status === 401) {
                errorMessage = '未授权，请重新登录'
            } else if (status === 403) {
                errorMessage = '没有权限删除此数据'
            } else if (status === 404) {
                errorMessage = '要删除的数据不存在'
            } else if (status === 500) {
                errorMessage = '服务器内部错误'
            } else {
                errorMessage = data?.message || `HTTP ${status} 错误`
            }
        } else if (error.message) {
            errorMessage = error.message
        }

        ElMessage.error(errorMessage)
    }
}

// 提交表单
const handleSubmit = async () => {
    if (!formRef.value) return

    try {
        await formRef.value.validate()
        submitLoading.value = true

        // 构建API请求数据
        const apiData: PopularizationData = {
            popularScienceTitle: formData.title,
            popularScienceImages: formData.image,
            diseaseType: `${formData.category}-${formData.subCategory}`,
            popularScienceStatus: formData.status,
            isRecommended: formData.isRecommend,
            detailedContent: formData.content
        }



        let response
        if (dialogType.value === 'add') {
            // 新增
            response = await addPopularization(apiData)
        } else {
            // 编辑
            response = await updatePopularization(formData.id, apiData)
        }



        if (response.data && response.data.code === 200) {
            ElMessage.success(dialogType.value === 'add' ? '新增成功' : '编辑成功')
            dialogVisible.value = false
            getDiseaseList()
        } else {
            ElMessage.error(response.data?.message || (dialogType.value === 'add' ? '新增失败' : '编辑失败'))
        }
    } catch (error) {
        console.error('提交失败:', error)

        // 详细的错误信息
        if (error && typeof error === 'object') {
            const errorObj = error as any
            if (errorObj.response) {
                const status = errorObj.response.status
                const data = errorObj.response.data
                console.error('HTTP错误:', { status, data })
                ElMessage.error(`请求失败 (${status}): ${data?.message || '未知错误'}`)
            } else if (errorObj.message) {
                console.error('错误消息:', errorObj.message)
                ElMessage.error(`操作失败: ${errorObj.message}`)
            } else {
                console.error('未知错误:', error)
                ElMessage.error(dialogType.value === 'add' ? '新增失败' : '编辑失败')
            }
        } else {
            console.error('错误对象:', error)
            ElMessage.error(dialogType.value === 'add' ? '新增失败' : '编辑失败')
        }
    } finally {
        submitLoading.value = false
    }
}

// 重置表单
const resetForm = () => {
    if (formRef.value) {
        formRef.value.resetFields()
    }
    Object.assign(formData, {
        id: 0,
        title: '',
        image: '',
        category: '',
        subCategory: '',
        status: true,
        isRecommend: false,
        content: ''
    })
    uploadSuccess.value = false
    console.log('表单已重置:', formData)
}

// 选择处理
const handleSelectionChange = (selection: any[]) => {
    selectedRows.value = selection
    selectAll.value = selection.length === tableData.value.length && tableData.value.length > 0
}

const handleSelectAll = (value: boolean) => {
    if (tableRef.value) {
        if (value) {
            tableRef.value.clearSelection()
            tableData.value.forEach(row => {
                tableRef.value.toggleRowSelection(row, true)
            })
        } else {
            tableRef.value.clearSelection()
        }
    }
}

// 分页处理
const handleSizeChange = (size: number) => {
    page.PageSize = size
    page.PageIndex = 1
    getDiseaseList()
}

const handleCurrentChange = (current: number) => {
    page.PageIndex = current
    getDiseaseList()
}

// 上传处理
const beforeUpload = (file: File) => {
    const isImage = file.type.startsWith('image/')
    const isLt1M = file.size / 1024 / 1024 < 1

    if (!isImage) {
        ElMessage.error('只能上传图片文件!')
        return false
    }
    if (!isLt1M) {
        ElMessage.error('图片大小不能超过 1MB!')
        return false
    }

    // 检查图片尺寸
    return new Promise((resolve) => {
        const reader = new FileReader()
        reader.onload = (e) => {
            const img = new Image()
            img.onload = () => {
                const width = img.width
                const height = img.height
                const recommendedWidth = 120
                const recommendedHeight = 90

                if (width !== recommendedWidth || height !== recommendedHeight) {
                    ElMessage.warning(`建议图片尺寸为 ${recommendedWidth}x${recommendedHeight}，当前尺寸为 ${width}x${height}`)
                }

                uploadLoading.value = true
                resolve(true)
            }
            img.src = e.target?.result as string
        }
        reader.readAsDataURL(file)
    })
}

const handleUploadSuccess = (response: any, file: File) => {
    console.log('上传响应:', response)
    uploadLoading.value = false

    if (response.code === 200) {
        // 根据API响应格式处理图片URL
        const imageUrl = response.data?.url || response.data || response
        formData.image = imageUrl

        // 显示上传成功状态
        uploadSuccess.value = true
        setTimeout(() => {
            uploadSuccess.value = false
        }, 2000)

        ElMessage.success('图片上传成功')
    } else {
        ElMessage.error(response.message || '上传失败')
    }
}

const handleUploadError = (error: any, file: File) => {
    console.error('Upload error:', error)
    console.error('Upload file:', file)
    uploadLoading.value = false
    ElMessage.error('上传失败，请检查网络连接或文件格式')
}

const handleUploadProgress = (event: any, file: File) => {
    // 上传进度处理
    console.log('上传进度:', event.percent)
}

// 重新上传图片
const reuploadImage = () => {
    formData.image = ''
    ElMessage.info('请重新选择图片上传')
}



// 富文本编辑器创建后的回调
const handleCreated = (editor: any) => {
    editorRef.value = editor
}

// 组件销毁前清理编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})

// 监听关键字变化，自动筛选
watch(() => filterForm.keyword, (newVal, oldVal) => {
    if (newVal !== oldVal) {
        // 防抖处理
        setTimeout(() => {
            handleFilterImmediate()
        }, 300)
    }
})

// 初始化
onMounted(() => {
    getDiseaseList()
})
</script>

<style scoped>
.disease-science-management {
    padding: 20px;
}

.disease-science-management h4 {
    margin: 0 0 20px 0;
    font-size: 20px;
    color: #333;
}

/* 筛选区域样式 */
.filter-card {
    margin-bottom: 20px;
}

.filter-container {
    padding: 10px 0;
}

.filter-item {
    display: flex;
    align-items: center;
    gap: 15px;
    flex-wrap: wrap;
}

.filter-label {
    font-size: 14px;
    color: #606266;
    white-space: nowrap;
}

/* 列表区域样式 */
.list-card {
    margin-bottom: 20px;
}

.list-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
}

.list-header h5 {
    margin: 0;
    font-size: 16px;
    color: #333;
}

.list-actions {
    display: flex;
    align-items: center;
    gap: 10px;
}

/* 分页区域样式 */
.pagination-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid #f0f0f0;
}

.pagination-left {
    display: flex;
    align-items: center;
    gap: 15px;
}

.pagination-info {
    color: #909399;
    font-size: 14px;
}

/* 上传区域样式 */
.image-upload {
    width: 200px;
}

.upload-area {
    width: 200px;
    height: 120px;
    border: 2px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: border-color 0.3s;
}

.upload-area:hover {
    border-color: #409eff;
}

.upload-placeholder {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    color: #999;
}

.upload-placeholder .el-icon {
    font-size: 28px;
    margin-bottom: 8px;
}

.upload-text {
    font-size: 14px;
}

.upload-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.3);
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: opacity 0.3s;
}

.upload-area:hover .upload-overlay {
    opacity: 1;
}

/* 上传成功提示样式 */
.upload-success-message {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: rgba(103, 194, 58, 0.9);
    color: white;
    padding: 8px 16px;
    border-radius: 20px;
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 14px;
    z-index: 10;
    animation: fadeInOut 2s ease-in-out;
}

@keyframes fadeInOut {
    0% {
        opacity: 0;
        transform: translate(-50%, -50%) scale(0.8);
    }

    20% {
        opacity: 1;
        transform: translate(-50%, -50%) scale(1);
    }

    80% {
        opacity: 1;
        transform: translate(-50%, -50%) scale(1);
    }

    100% {
        opacity: 0;
        transform: translate(-50%, -50%) scale(0.8);
    }
}

.upload-tip {
    margin-top: 8px;
    font-size: 12px;
    color: #999;
}

/* 图片信息显示样式 */
.image-info {
    margin-top: 10px;
    display: flex;
    align-items: center;
    gap: 10px;
}

.image-info .el-tag {
    margin-right: 10px;
}

.image-info .el-button {
    margin-left: auto;
}

/* 富文本编辑器样式 */
.rich-text-editor {
    border: 1px solid #ccc;
    border-radius: 4px;
    overflow: hidden;
}

.rich-text-editor:focus-within {
    border-color: #409eff;
    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

/* 对话框样式 */
.dialog-footer {
    text-align: right;
}

/* 详情页样式 */
.disease-detail {
    padding: 20px;
}

.detail-section {
    margin-bottom: 30px;
}

.detail-section h3 {
    color: #333;
    font-size: 18px;
    margin-bottom: 15px;
    padding-bottom: 8px;
    border-bottom: 2px solid #f0f0f0;
}

.detail-content {
    display: flex;
    gap: 20px;
}

.detail-left {
    flex-shrink: 0;
}

.detail-right {
    flex: 1;
}

.detail-table {
    width: 100%;
    border-collapse: collapse;
}

.detail-table td {
    padding: 8px 12px;
    border: 1px solid #e4e7ed;
    font-size: 14px;
}

.detail-table .label {
    background-color: #f5f7fa;
    font-weight: 500;
    width: 100px;
}

.disease-content {
    line-height: 1.6;
    color: #666;
}

/* 富文本内容样式 */
.rich-content {
    line-height: 1.6;
    color: #666;
}

.rich-content p {
    margin-bottom: 15px;
    margin-top: 0;
}

.rich-content h1,
.rich-content h2,
.rich-content h3,
.rich-content h4,
.rich-content h5,
.rich-content h6 {
    margin-top: 20px;
    margin-bottom: 10px;
    color: #333;
}

.rich-content ul,
.rich-content ol {
    margin-bottom: 15px;
    padding-left: 20px;
}

.rich-content img {
    max-width: 100%;
    height: auto;
    border-radius: 4px;
    margin: 10px 0;
}

.rich-content blockquote {
    margin: 15px 0;
    padding: 10px 15px;
    background-color: #f8f9fa;
    border-left: 4px solid #409eff;
    color: #666;
}

.rich-content code {
    background-color: #f1f2f3;
    padding: 2px 4px;
    border-radius: 3px;
    font-family: monospace;
    color: #e74c3c;
}

.rich-content pre {
    background-color: #f8f9fa;
    padding: 15px;
    border-radius: 4px;
    overflow-x: auto;
    margin: 15px 0;
}

.rich-content a {
    color: #409eff;
    text-decoration: none;
}

.rich-content a:hover {
    text-decoration: underline;
}

.default-content p {
    margin-bottom: 15px;
    margin-top: 0;
}

/* 删除确认对话框样式 */
.delete-confirm-dialog .el-message-box__content {
    white-space: pre-line;
    line-height: 1.6;
}

.batch-delete-confirm-dialog .el-message-box__content {
    white-space: pre-line;
    line-height: 1.6;
    max-height: 400px;
    overflow-y: auto;
}

.delete-confirm-dialog .el-message-box__message,
.batch-delete-confirm-dialog .el-message-box__message {
    text-align: left;
    font-size: 14px;
}

/* 删除按钮样式优化 */
.el-button--danger.is-loading {
    background-color: #f56c6c;
    border-color: #f56c6c;
    color: #fff;
}

/* 表格操作按钮组样式 */
.el-table .el-button+.el-button {
    margin-left: 8px;
}

/* 批量操作区域样式 */
.pagination-left .el-button--danger {
    margin-left: 10px;
}

/* 选中状态提示 */
.pagination-left .el-checkbox {
    margin-right: 15px;
}
</style>